let questionDao = require('../dao/questionDao');
let stringUtil = require("../util/stringUtil");
let redis = require('../dao/redis');

let assert = require('assert');

const { BusiError, SysError } = require('../exception/exception');

class QuestionService{
    constructor(){}

    /**
     *
     * @param question
     * @param        {String} question.uid
     * @param        {String} question.question
     * @returns {Promise<void>}
     */
    async saveQuestion(question) {
        let lockKey = "qs:ask:" + question.uid;
        let isSucc = await redis.lock(lockKey, 1, 10);
        if (!isSucc){
            throw new BusiError(500, "咨询太频繁");
        }

        let affected = await questionDao.save(question);
        if (affected < 1){
            throw new BusiError(500, "提问失败");
        }
    }

    /**
     *
     * @param cond
     * @param     {String} cond.id
     * @param     {String} cond.answer
     * @returns {Promise<void>}
     */
    async answerQuestion(cond){
        let lockKey = "qs:answer:" + cond.id;
        let isSucc = await redis.lock(lockKey, 1, 10);
        if (!isSucc){
            throw new BusiError(500, "提交太频繁");
        }

        let qs = await questionDao.get(cond.id);
        if (!qs){
            throw new BusiError(500, "该问题不存在");
        }

        let res = await questionDao.updateById(cond);
        if (res === 0) {
            throw new BusiError(500, "提交失败");
        }

        let cacheKey = "as:record:" + qs.uid;
        await redis.del(cacheKey);
    }

    /**
     *
     * @param cond
     * @param     {String} cond.uid
     * @param     {String} cond.startTime
     * @param     {String} cond.endTime
     * @param     {String} cond.page
     * @param     {String} cond.status
     * @returns {Promise<void>}
     */
    async queryQuestion(cond){
        return await questionDao.queryByCond(cond);
    }

    /**
     *
     * @param {String} cond.uid
     * @returns {Promise<Object>}
     */
    async queryQuestionByUid(cond){
        let cacheKey = "as:record:" + cond.uid;
        let cache = await redis.get(cacheKey);
        if (!cache){
            let res = await questionDao.queryByUid(cond.uid);

            cache = res;

            await redis.set(cacheKey, cache, 600);
        }

        return cache;
    }

    /**
     *
     * @param {String} cond.id
     * @param {String} cond.uid
     * @returns {Promise<*|number>}
     */
    async setQuestionReadByIdAndUid(cond){
        let res = await questionDao.setReadById(cond);
        if (res > 0){
            let cacheKey = "as:record:" + cond.uid;
            await redis.del(cacheKey);
        }

        return res;
    }
}

let questionService = new QuestionService();
module.exports = questionService;